#!/usr/bin/php
<?php

require_once __DIR__ . '/vendor/autoload.php';

if (empty($argv[1])) {
    fwrite(STDERR, 'Please specify file path(s).');
    return;
}
$filepaths = $argv;
array_shift($filepaths);
foreach ($filepaths as $filepath) {
    if (!file_exists($filepath)) {
        fwrite(STDERR, "file {$filepath} not exists.");
        return;
    }
}

foreach ($filepaths as $filepath) {
    $contents = file_get_contents($filepath);
    $tokens = token_get_all($contents);
    $tokens = array_map(function($x) {
        if (is_array($x)) {
            $x[] = token_name($x[0]);
        }
        return $x;
    }, $tokens);
    // \Symfony\Component\VarDumper\VarDumper::dump($tokens);die();

    $closeLevel = 0;
    foreach ($tokens as $i => $token) {
        if (is_array($token)) {
            continue;
        }

        if ($token == '[') {
            for ($j = $i - 1; $j >= 0; $j -= 1) {
                // dump($tokens[$j]);

                if (!is_array($tokens[$j])) {
                    if ($tokens[$j] == ']') {
                        break;
                    }
                } else {
                    if ($tokens[$j][0] == T_WHITESPACE) {
                        continue;
                    }
                    if ($tokens[$j][0] == T_VARIABLE) {
                        break;
                    }
                    if ($j - 1 >= 0 && $tokens[$j - 1][0] == T_OBJECT_OPERATOR) {
                        break;
                    }
                }
                $closeLevel += 1;
            }

            if ($closeLevel > 0) {
                $tokens[$i] = 'array(';
            }

            // dump($closeLevel);
        }

        if ($token == ']') {
            if ($closeLevel > 0) {
                $tokens[$i] = ')';
                $closeLevel -= 1;
            }

            // dump($closeLevel);
        }
    }

    $output = implode('', array_map(function($x) {
        if (is_array($x)) {
            return $x[1];
        }
        return $x;
    }, $tokens));

    $output = $output . "\n";
    file_put_contents($filepath, $output);
}
